package jys.test.yddata.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;

import androidx.constraintlayout.widget.ConstraintLayout;

import java.util.Iterator;
import java.util.List;

import jys.test.yddata.R;

/**
 * 标签按钮阵列
 * @author Yunsong Jia
 */
public class LabelTable extends TableLayout {
    private View nowaLabel; // 当前已按下的按钮

    public LabelTable(Context context) {
        super(context);
    }

    public LabelTable(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 添加标签列表
     * @param columnCount 列数量
     * @param labels 标签列表
     */
    public void addLabels(int columnCount, List<String> labels) {
        addLabels(columnCount, labels.iterator().next(), labels);
    }

    /**
     * 添加标签列表
     * @param columnCount 列数量
     * @param defaultLabel 默认选取的标签
     * @param labels 标签列表
     */
    public void addLabels(int columnCount, String defaultLabel, List<String> labels) {
        if (!labels.contains(defaultLabel))
            throw new AssertionError("defaultLabel not in labels");
        if (labels.size() < 4)
            columnCount = labels.size();

        TableRow tbrow = null; Button bt; String lb;
        Iterator it = labels.iterator();
        int wi = getWidth()/columnCount;
        int hi = getHeight()/((labels.size()+2)/columnCount);
        for(int i=0; i<labels.size(); i++) {
            if(i % columnCount == 0) {
                tbrow = new TableRow(getContext());
                addView(tbrow);
            }
            lb = (String) it.next();
            bt = new Button(getContext());
            bt.setText(lb);
            bt.setOnClickListener(this::directButtonChange);
            setButtonStyle(bt, wi, hi);
            tbrow.addView(bt);
            if(lb.equals(defaultLabel)) {
                bt.setEnabled(false);
                nowaLabel = bt;
            }
        }
    }

    /**
     * 获取当前选中的标签
     * @return 当前选择的标签名称
     */
    public String getLabel() {
        return (String) ((Button) nowaLabel).getText();
    }

    @SuppressLint("ResourceType")
    private void setButtonStyle(Button bt, int wi, int hi) {
        bt.setBackgroundResource(R.drawable.cli_drawable);
        bt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
        bt.setTextColor(Color.parseColor("#000000"));
        bt.setWidth(wi);
        bt.setHeight(hi);
    }

    private void directButtonChange(View v) {
        nowaLabel.setEnabled(true);
        v.setEnabled(false);
        nowaLabel = v;
    }

    public void setHeight(int h) {
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) this.getLayoutParams();
        params.height = h;
        this.setLayoutParams(params);
    }
}
